#include <stdio.h>

void swap(int* a1, int* a2)
{
    int tmp = *a1;
    *a1 = *a2;
    *a2 = tmp;
}

void adjust(int* array, int nCnt, int root)
{
    int nParent = root;
    int nChild = nParent * 2 + 1;
    while (nChild < nCnt)
    {
        if (nChild + 1 < nCnt && array[nChild + 1] > array[nChild])
            nChild += 1;

        if (array[nChild] <= array[nParent]) break;

        swap(&array[nChild], &array[nParent]);
        nParent = nChild;
        nChild = nParent * 2 + 1;
    }
}

void sort(int* array, int nCnt)
{
    int nEnd = nCnt - 1;

    for (int i = (nCnt - 1 - 1) / 2; i >= 0; i--)
        adjust(array, nCnt, i);

    while (nEnd > 0)
    {
        swap(&array[0], &array[nEnd]);
        adjust(array, nEnd, 0);
        nEnd--;
    }
}

int main()
{
    int array[9] = { 2,8,5,1,3,11,7,2,6 };

    sort(array, sizeof(array) / sizeof(int));

    for (unsigned int i = 0; i < (sizeof(array) / sizeof(int)); ++i)
        printf("%d ", array[i]);
    puts("");

    return 0;
}